<?php
class ObjectToXML
{
    private $dom;
    public function __construct ($obj)
    {
        $this->dom = new DOMDocument("1.0", "UTF8");
        $root = $this->dom->createElement('response');
        foreach ($obj as $key => $value) {
            if (is_numeric($key))
    {
    // make string key...
    $key = "Item";
    }
     
    // replace anything not alpha numeric
    $key = preg_replace('/_[0-9]/i', '', $key);
            $node = $this->createNode($key, $value);
            if ($node != NULL)
                $root->appendChild($node);
        }
        $this->dom->appendChild($root);
    }
    private function createNode ($key, $value)
    {
        try {
            $node = NULL;
            if (is_string($value) || is_numeric($value) || is_bool($value) || $value == NULL) {
                if ($value == NULL)
                    $node = $this->dom->createElement($key);
                else
                    $node = $this->dom->createElement($key,  htmlspecialchars($value));
            } else {
                $node = $this->dom->createElement($key);
                if ($value != NULL) {
                    foreach ($value as $key => $value) {
                        if (is_numeric($key))
                                {
                                // make string key...
                                $key = "sub_item". (string) $key;
                                }
     
                            // replace anything not alpha numeric
                        $key = preg_replace('/_[0-9]/i', '', $key);
                        $sub = $this->createNode($key, $value);
                        if ($sub != NULL)
                            $node->appendChild($sub);
                    }
                }
            }
            
            return $node;
           
        } catch (Exception $ex) {
             print_r($ex);   
        }

        return null;
    }
    
    public function __toString ()
    {
        return $this->dom->saveXML();
    }
}